# 【3.股东变化】-累计占流通股比例
import csv
import re
from datetime import datetime

from common import bin_storage


class ContentHandler:
    def __init__(self):
        self._res = dict()

    def get_res(self):
        return self._res

    def handle(self, row):  # main
        code, content = row["code"], row["content"]
        self._flag4(code, content)

    def _flag4(self, code, content):
        if content == "EMPTY":
            self._res[code] = content
            return
        s = self.extractor(content)
        self._res[code] = s

    def extractor(self, content):
        s = '(' + re.search('更新日期[：:][\d]{4}-([\d]{2}-[\d]{2})◇', content).group(1) + ")\n"
        body = re.search('【3\.股东变化】[\s\S]+【3\.股东变化】([\s\S]+)【4\.', content)
        if body is None:
            body = re.search('【3\.股东变化】[\s\S]+【3\.股东变化】([\s\S]+)$', content)
            if body is None:
                return "空" + s
        body = body.group(1)
        body_list = body.split('截至日期')
        for i in body_list:
            if len(i.strip()) == 0 or '累计占流通股比例' not in i:
                continue

            date, per, fluctuation = re.search(
                '[：:][\d]{2}([\d]{2}-[\d]{2}-[\d]{2})[^~~]*?累计占流通股比例[：:]([\d.-]+%)[^%]*较上期变化[：:](.+)\n', i).groups()
            # print(fluctuation.encode('gbk'))
            table_list = re.search('─────────────────────────────────────([^~~]+)─────────────────────────────────────',
                                   i).group(1).split('─────────────────────────────────────')
            current = table_list[0].strip()
            withdraw = table_list[-1].strip('\n')
            s += '++++++++++++++++++++ {}  {}  {} ++++++++++++++++++++\n'.format(date, per, fluctuation.strip())
            s += '股东名称 (单位:万股)            持股数 占流通股比(%)  股东性质    增减情况\n' + current + '\n───────────────────────────────────────\n' + withdraw + '\n'
        return s


# find interesting parts of a given raw csv
def run(path_to_process, g_path=''):
    print("--------------------- f10b started.  --------------------")
    file_name = path_to_process
    with open(file_name, newline='', encoding="utf-8-sig", errors="ignore") as csvfile:
        reader = csv.DictReader(csvfile)
        handler = ContentHandler()
        for row in reader:
            if row['flag'] == '4':
                handler.handle(row)
        ana_res = handler.get_res()
        bin = bin_storage.Bin_storage()
        save_bin_name = g_path + 'bin/' + datetime.today().strftime('%Y-%m-%d')
        bin.save(save_bin_name, ana_res)

        print("--------------------- f10b finished.  --------------------")


if __name__ == '__main__':
    run("../f10a/res_2020-07-15.csv", g_path="")
